/* Copyright (c) 2009-2010, Sean A.O. Harney <sharney3@gmail.com> */

#include "omf.h"


//expects already evaled leaf expr of INT or STRING
EXPR_P builtin_func_sleep(EXPR_P expr)
{
    unsigned secs = 0;

    if (expr->type != EXPR_LEAF
	|| (expr->u.leaf.type != LEAF_INT
	    && expr->u.leaf.type != LEAF_STRING))
	fatal_error_println
	    ("OMF built-in function sleep() expects INT or STRING expr as argument.");

    if (expr->u.leaf.type == LEAF_INT)
      {
	  INTVAL_P iv = expr->u.leaf.val.int_val;
	  if (iv->negative)	//the grammar can't enforce builtin-func arg types
	    {
		error_println
		    ("Warning: built-in function sleep() called with negative value. Instead sleeping for 0 seconds");
		//secs = 0 still.
	  } else
	      secs = iv->ulong_val;
    } else if (expr->u.leaf.type == LEAF_STRING)
      {
	  char *str = expr->u.leaf.val.string_val;
	  /* inspired by sleep(1) linux cmd */
	  if (strlen(str) == 0)
	      fatal_error_println
		  ("Sleep \"\" not allowed. Cannot used sleep with empty string!");

	  int i;
	  int mult;
	  char *p = str + strlen(str) - 1;
	  char suffix = *p;


	  *p = '\0';		/* tie off str. p is ptr into str */

// convert to seconds
	  mult = 1;
	  switch (suffix)
	    {
	    case 'd':
		mult *= 24;	/* 24*60*60 s */
		/* fall through */
	    case 'h':
		mult *= 60;	/* 60*60 s */
		/* fall through */
	    case 'm':
		mult *= 60;	/* 60 s */
		/* fall through */
	    case 's':
		/* secs *= 1; 1s */
		i = atoi(str);	//TODO: eror check;
		secs = mult * i;
		break;
	    default:
		yyerror_println
		    ("invalid sleep time: %s%c: invalid suffix '%d'", str,
		     suffix, suffix);
	    }
      }

    debug1_printf("Sleeping %d seconds.\n", secs);
    sleep(secs);
    debug1_printf("Finished sleeping.\n");

    return new_expr_leaf_bool(true);
}
